#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "parse.h"

void parse_cmd(char *line,struct cmd *cmd)
{
    cmd->argc=0;
    cmd->input = NULL;
    cmd->output = NULL;
    const char delim[] = " ";
    char *tok;
    char *saveptr;
    tok = strtok_r(line, delim, &saveptr);
    while(tok != NULL) {
        if(tok[0] == '<') {
            cmd->input = tok;
            cmd->input++;
            break;
        }
        else if(tok[0] == '>') {
            cmd->output = tok;
            cmd->output++;
            break;
        }
        else {
            cmd->argv[cmd->argc] = tok;
            cmd->argc++;
        }
        tok = strtok_r(NULL, delim, &saveptr);
    }
    cmd->argv[cmd->argc]=NULL;
}

void dump_cmd(struct cmd *cmd)
{
    printf("argc = %d\n",cmd->argc);
    int i;
    for(int i=0; i < cmd->argc; i++) {
        printf("argv[%d] = (%s)\n", i, cmd->argv[i]);
    }

    char *input = cmd->input ? cmd->input : "NULL";
    printf("input = (%s)\n", input);

    char *output = cmd->output ? cmd->output : "NULL";
    printf("output = (%s)\n", output);
}

int parse_pipe_cmd(char *line, struct cmd *cmdv)
{
    int cmdc=0;
    char *token;
    char *saveptr;
    token = strtok_r(line, "|", &saveptr);
    while(token != NULL) {
        parse_cmd(token, &cmdv[cmdc]);
        cmdc++;
        token = strtok_r(NULL, "|", &saveptr);
    }
    return cmdc;
}

void dump_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int i;
    printf("pipe cmd, cmdc = %d\n", cmdc);
    for(i = 0; i < cmdc; i++) {
        struct cmd *cmd = cmdv + i;
        dump_cmd(cmd);
    }
}
